from common.sys.shell import Shell
from common.utils.toolkit import Log
import copy

import os,base64
class MediaFile():
    __instance = None
    MEIDA_FILE_MIME = [".MP4",".MKV",".WEBM",".AVI"]

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        try:
            len(self.mediaFilesMap.keys())
        except:
            self.mediaFilesMap = {}

    def updateSnapShot(self):
        for file in self.mediaFilesMap.values():
            if('snapshot' not in file.keys()):
                Log.i("snapshot for {}".format(file['path']))
                file['snapshot'] = self.snapshot(file['path'], 3)
        return self.mediaFilesMap

    def snapshot(self, path, num):
        image = "./snap.jpg"
        timestamp = 360
        snapshotList = []
        for offset in range(num):
          cmd = " ".join(["ffmpeg", "-ss", str(timestamp), "-i", path, "-r", "1", "-frames:v", "1", "-s", "352x288", "-q:v", "2", "-f", "image2", "-y", image])
          Shell.exec(cmd, True)
          timestamp += 10*60
          with open(image, 'rb') as f:
            imgfile = f.read()
            snapshotList.append(str(base64.b64encode(imgfile), encoding='utf-8'))
        return snapshotList

    def queryMediaFiles(self, rootpath, hidedir=None):
        self.mediaFilesMap = self.__queryMediaFiles(rootpath, {}, hidedir)
        return self.mediaFilesMap

    def __queryMediaFiles(self, rootpath, list, hidedir):
        if(hidedir is None):
            hidedir = rootpath
        for file in self.mediaFilesMap.keys():
            Log.d("OLD Files:{}:{}".format(file, self.mediaFilesMap[file]))
        for root, dirs, files in os.walk(rootpath):
            for name in files:
                mime = os.path.splitext(name)[-1]
                if(mime.upper() in MediaFile.MEIDA_FILE_MIME):
                    path = os.path.join(root, name)
                    id = base64.b64encode(path.encode('utf-8')).decode()
                    Log.d("{} ID:{}".format(path, id))
                    if(id in self.mediaFilesMap.keys()):
                        list[id] = copy.deepcopy(self.mediaFilesMap[id])
                    else:
                        Log.i("Found a NEW file:{}".format(path))
                        list[id] = self.loadFileInfo(path, name, mime)
        return list 

    def loadFileInfo(self, path, name, mime):
       id = base64.b64encode(path.encode('utf-8')).decode()
       cmd = "ffprobe -show_entries format=duration -v quiet -of flat -i {}".format(path)
       duration = Shell.exec(cmd,True)
       Log.d("{} duration is:{}".format(path, duration))
       duration = float(duration.split("=\"")[1].rstrip("\"\n"))
       name = name.replace(mime,"")
       return {'name': name, 'path':path, 'id':id, 'duration':duration}
